package com.example.nfc.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.nfc.MainActivity;
import com.example.nfc.R;
import com.example.nfc.barcodescan.android.CaptureActivity;
import com.example.nfc.barcodescan.common.Constant;
import com.example.nfc.base.BaseNfcActivity;
import com.example.nfc.dialog.AlertDialog;
import com.example.nfc.dialog.BaseDialog;
import com.example.nfc.dialog.SelectDialog;
import com.example.nfc.server.Const;
import com.example.nfc.server.network.http.HttpException;
import com.example.nfc.server.request.CardRequest;
import com.example.nfc.server.response.Admin;
import com.example.nfc.server.response.Card;
import com.example.nfc.server.response.CardInfo;
import com.example.nfc.server.response.Cate;
import com.example.nfc.server.response.ListCate;
import com.example.nfc.server.response.Respone;
import com.example.nfc.server.utils.CommonUtils;
import com.example.nfc.server.utils.DateUtil;
import com.example.nfc.server.utils.NLog;
import com.example.nfc.server.utils.Output;
import com.example.nfc.server.utils.SharedPreferencesUtil;
import com.example.nfc.tools.CheckPermissionUtil;
import com.example.nfc.tools.DeviceReceiver;
import com.example.nfc.tools.ScannerKeyEventHelper;
import com.yanzhenjie.permission.Permission;

import net.posprinter.posprinterface.IMyBinder;
import net.posprinter.posprinterface.ProcessData;
import net.posprinter.posprinterface.TaskCallback;
import net.posprinter.service.PosprinterService;
import net.posprinter.utils.DataForSendToPrinterTSC;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AdminActivity extends BaseNfcActivity implements ScannerKeyEventHelper.OnScanSuccessListener {

    private ScannerKeyEventHelper mScannerKeyEventHelper;
    private static IMyBinder myBinder;

    ServiceConnection mSerconnection= new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder= (IMyBinder) service;
            Log.e("myBinder","connect");
            if(printerMac!=null){
                connectPrinter();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("myBinder","disconnect");
        }
    };


    private String code = null;
    private boolean IS_JIHUO=true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write_text);
        ButterKnife.bind(this);
        mScannerKeyEventHelper = new ScannerKeyEventHelper(this);
        Intent intent =new Intent(this, PosprinterService.class);
        bindService(intent,mSerconnection,BIND_AUTO_CREATE);

        inflate = LayoutInflater.from(this);
        String uname = getData(Const.USERNAME,"");

        String cate_id = getData("cate_id","");
        String cate_name = getData("cate_name","");
        if(!TextUtils.isEmpty(cate_id)){
            cateId = cate_id;
        }
        if(!TextUtils.isEmpty(cate_name)){
            cate.setText(cate_name);
        }

        username.setText("当前登录:"+uname);
        String l = getData(Const.LOG,"");
        if(!TextUtils.isEmpty(l)){
            log.setText(l);
        }
        printerMac = SharedPreferencesUtil.getData(Const.MAC,null);
        IS_JIHUO = getData(Const.IS_JIHUO,true);
        if(IS_JIHUO){
            CommonUtils.setRadioButtonDrawable(this,rg,rb_1,0);
        }else{
            CommonUtils.setRadioButtonDrawable(this,rg,rb_2,1);
        }
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = group.findViewById(checkedId);
                int position = 0 ;
                if(checkedId==R.id.rb_1){
                    position = 0 ;
                    IS_JIHUO=true;
                    putData(Const.IS_JIHUO,true);
                }else{
                    position = 1 ;
                    IS_JIHUO=false;
                    putData(Const.IS_JIHUO,false);
                }
                CommonUtils.setRadioButtonDrawable(AdminActivity.this,rg,radioButton,position);
            }
        });
    }
    @OnClick(R.id.clean)
    public void cleanClick(){
        code = "";
        boolean wr =  writeCard(detectedTag);
        if(wr){
            print(true,"已清除卡片数据");
        }else {
            print(false,"卡片数据清除失败");
        }
    }

    @Bind(R.id.rg)
    RadioGroup rg;
    @Bind(R.id.rb_1)
    RadioButton rb_1;
    @Bind(R.id.rb_2)
    RadioButton rb_2;
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        mScannerKeyEventHelper.analysisKeyEvent(event);
        return super.dispatchKeyEvent(event);
    } /**
     * 扫描成功回调
     * @param barcode
     */
    private boolean isShaoMa = false;
    @Override
    public void onScanSuccess(String barcode) {
        if(!TextUtils.isEmpty(barcode)){
            print(true,"已扫码到二维码,内码编号为:"+barcode);
            isActivie = true;
            cardId = barcode;
            isShaoMa = true;
            request(GET_CODE);
        }
    }

        private String printerMac = null;

    @Bind(R.id.connect)
    Button connect;
    @OnClick(R.id.connect)
    public void connectClick(){
        setBluetooth();
    }

    @OnClick(R.id.clear)
    public void clearClick(){
        log.setText("");
        putData(Const.LOG,"");
    }
    @OnClick(R.id.logout)
    public void logoutClick(){
        request(LOGIN_OUT);
    }


    @Bind(R.id.username)
    TextView username;
    @Bind(R.id.log)
    TextView log;

    @Override
    protected void onDestroy() {
        putData(Const.LOG,log.getText().toString());
        unbindService(mSerconnection);
        super.onDestroy();
    }

    private static final int LOGIN_OUT = 1000;
    private static final int GET_CODE = 1001;
    private static final int GET_CATE = 1061;
    private static final int SAVE_CODE = 1002;
    private static final int SAVE_LIST_CODE = 1003;

    private String cardId;
    private CardRequest cardRequest;
    private List<CardRequest> cardListRequest;
    private AlertDialog alertDialog;
    @Override
    public Object doInBackground(int requestCode, String parameter) throws HttpException {
        switch (requestCode){
            case GET_CATE:
                return action.getCardCateRequest();
            case LOGIN_OUT:
                return action.getLogoutRequest();
            case GET_CODE:
                return action.getCardRequest(cardId);
            case SAVE_CODE:
                return action.saveCardRequest(cardRequest);
            case SAVE_LIST_CODE:
                return action.saveCardRequest(cardListRequest);
        }
        return super.doInBackground(requestCode, parameter);
    }

    private SelectDialog selectDialog;
    @Override
    public void onSuccess(int requestCode, Object result) {
        super.onSuccess(requestCode, result);
        switch (requestCode){
            case GET_CATE:
                ListCate listCate = (ListCate)result;
                lastCate = listCate.getCard_cate();
                selectCate();
                break;
            case LOGIN_OUT:
                startActivityAndFinish(MainActivity.class);
                break;
            case SAVE_LIST_CODE:
            Respone responeList = (Respone)result;
                if(responeList.getCode()==200){
                        print(true,"卡片绑定进销商并激活成功!");
                        cardInfoList.clear();
                        cardInfoList = null;
                        toPrintCardInfo();
                }else{
                        print(false,"卡片绑定进销商并激活失败,请重试!");
                }
                break ;
            case SAVE_CODE:
                Respone respone = (Respone)result;
                if(respone.getCode()==200){
                    if(isActivie){
                        isActivie=false;
                        print(true,"卡片激活成功!!");
                    }else{
                        print(true,"保存到云端成功!");
                    }
                }else{
                    if(isActivie){
                        isActivie= false;
                        print(false,"卡片激活失败,请重试!");
                    }else {
                        print(false,"保存到云端失败,请重试!");
                    }
                }
                break;
            case GET_CODE:
                Card card = (Card)result;
                if(card!=null){
                    if(isActivie){
                        CardInfo cardInfo = card.getCard();
                        if(cardInfo==null){
                            isActivie = false;
                            print(false,"非法卡！此卡片不存在系统中..");
                            alertDialog = new AlertDialog(AdminActivity.this);
                                alertDialog.setTitle("是否刷入新卡?");
                                alertDialog.setContent("此卡片不存在系统中，是否刷入新卡?");
                                alertDialog.setSubmitTxt("刷入新卡");
                                alertDialog.setCancelTxt("取消");
                                alertDialog.hideJihuo();
                                alertDialog.setOnResult(new BaseDialog.OnResult() {
                                    @Override
                                    public void onActive() {

                                    }

                                    @Override
                                    public void onYes() {
                                        if(cateId==null){
                                            print(false,"请先选择卡片分类！");
                                            getCate();
                                            return;
                                        }
                                        Card card = alertDialog.card;
                                        code = card.getCard1();
                                        boolean wr =  writeCard(detectedTag);
                                        String catename = cate.getText().toString();
                                        if(!TextUtils.isEmpty(catename)){
                                            card.setCard1(card.getCard1().replace("WM",catename+"-"));
                                        }
                                        if(wr){
                                            print(true,"外码:"+card.getCard1()+",内码:"+card.getCard2()+"写入成功!");
                                            cardRequest = new CardRequest();
                                            //cardRequest.setId(card.getCard().getCard_id()+"");
                                            cardRequest.setOut(card.getCard1());
                                            cardRequest.setInner(card.getCard2());
                                            //cardRequest.setAdmin_id(card.getCard().getShare_admin_id());
                                            if(cateId!=null){
                                                cardRequest.setCate_id(cateId);
                                            }
                                            cardRequest.setState("0");
                                            request(SAVE_CODE);
                                        }else{
                                            print(false,"写入失败！可能您已经移开了卡片");
                                        }
                                    }

                                    @Override
                                    public void onNo() {

                                    }
                                });
                            if(!alertDialog.isShowing()){
                                alertDialog.card = card;
                                alertDialog.show(0,Gravity.CENTER);
                            }
                            return;
                        }
                        if(cardInfo.getIs_del()==1){
                            isActivie = false;
                            print(false,"此卡片已被管理员删除,请选择操作...");

                                alertDialog = new AlertDialog(AdminActivity.this);
                                alertDialog.setTitle("是否刷入新卡?");
                                alertDialog.setContent("此卡片已被管理员删除，是否刷入新卡?");
                                alertDialog.setSubmitTxt("刷入新卡");
                                alertDialog.setCancelTxt("取消");
                                alertDialog.hideJihuo();
                                alertDialog.setOnResult(new BaseDialog.OnResult() {
                                    @Override
                                    public void onActive() {

                                    }

                                    @Override
                                    public void onYes() {
                                        if(cateId==null){
                                            print(false,"请先选择卡片分类！");
                                            getCate();
                                            return;
                                        }
                                        Card card = alertDialog.card;
                                        code = card.getCard1();
                                        boolean wr =  writeCard(detectedTag);
                                        String catename = cate.getText().toString();
                                        if(!TextUtils.isEmpty(catename)){
                                            card.setCard1(card.getCard1().replace("WM",catename+"-"));
                                        }
                                        if(wr){
                                            print(true,"外码:"+card.getCard1()+",内码:"+card.getCard2()+"写入成功!");
                                            cardRequest = new CardRequest();
                                            cardRequest.setId(card.getCard().getCard_id()+"");
                                            cardRequest.setOut(card.getCard1());
                                            cardRequest.setInner(card.getCard2());
                                            cardRequest.setAdmin_id(card.getCard().getShare_admin_id());
                                            if(cateId!=null){
                                                cardRequest.setCate_id(cateId);
                                            }
                                            cardRequest.setState("0");
                                            request(SAVE_CODE);
                                        }else{
                                            print(false,"写入失败！可能您已经移开了卡片");
                                        }
                                    }

                                    @Override
                                    public void onNo() {

                                    }
                                });
                            if(!alertDialog.isShowing()){
                                alertDialog.card = card;
                                alertDialog.show(0,Gravity.CENTER);
                            }
                            return;
                        }
                        if(cardInfo.getState()==1){
                            isActivie = false;
                            if(!TextUtils.isEmpty(cardInfo.getShare_user_id())){
                                isActivie = false;
                                print(false,"此卡片已兑卡,请选择操作...");

                                alertDialog = new AlertDialog(AdminActivity.this);
                                alertDialog.setTitle("是否刷入新卡?");
                                alertDialog.setContent("此卡片已兑卡，是否刷入新卡?");
                                alertDialog.setSubmitTxt("刷入新卡");
                                alertDialog.setCancelTxt("取消");
                                alertDialog.hideJihuo();
                                alertDialog.setOnResult(new BaseDialog.OnResult() {
                                    @Override
                                    public void onActive() {

                                    }

                                    @Override
                                    public void onYes() {
                                        if(cateId==null){
                                            print(false,"请先选择卡片分类！");
                                            getCate();
                                            return;
                                        }
                                        Card card = alertDialog.card;
                                        code = card.getCard1();
                                        boolean wr =  writeCard(detectedTag);
                                        if(card.getCard()!=null){
                                            String catename = card.getCard().getCard_out();
                                            catename = catename.substring(0,catename.indexOf("-"));
                                            if(!TextUtils.isEmpty(catename)){
                                                card.setCard1(card.getCard1().replace("WM",catename+"-"));
                                            }
                                        }else{
                                            String catename = cate.getText().toString();
                                            if(!TextUtils.isEmpty(catename)){
                                                card.setCard1(card.getCard1().replace("WM",catename+"-"));
                                            }
                                        }
                                        if(wr){
                                            print(true,"外码:"+card.getCard1()+",内码:"+card.getCard2()+"写入成功!");
                                            cardRequest = new CardRequest();
                                            cardRequest.setId(card.getCard().getCard_id()+"");
                                            cardRequest.setOut(card.getCard1());
                                            cardRequest.setInner(card.getCard2());
                                            cardRequest.setAdmin_id(card.getCard().getShare_admin_id());
                                            if(cateId!=null){
                                                cardRequest.setCate_id(cateId);
                                            }
                                            cardRequest.setState("0");
                                            request(SAVE_CODE);
                                        }else{
                                            print(false,"写入失败！可能您已经移开了卡片");
                                        }
                                    }

                                    @Override
                                    public void onNo() {

                                    }
                                });
                                if(!alertDialog.isShowing()){
                                    alertDialog.card = card;
                                    alertDialog.show(0,Gravity.CENTER);
                                }
                                return;
                            }else{
                                //已激活的
                                printQrCode(cardInfo.getCard_inner());
                            }
                        }else{
                            if(IS_JIHUO) {
                                if (cardInfoList == null) {
                                    cardInfoList = new ArrayList<>();
                                }
                                if (check(cardInfo)) {
                                    print(true, "批量操作列表已存在该条码!");
                                    return;
                                }
                                cardInfoList.add(cardInfo);
                                lastAdmin = card.getAdmin();
                                toPrintCardInfo();
                            }else{
                                isActivie = false;
                                //未激活的
                                printQrCode(cardInfo.getCard_inner());
                            }
                        }
                    }else{
                        if(cateId==null){
                            print(false,"请先选择卡片分类！");
                            getCate();
                            return;
                        }
                        code = card.getCard1();
                        boolean wr =  writeCard(detectedTag);
                        String catename = cate.getText().toString();
                        if(!TextUtils.isEmpty(catename)){
                            card.setCard1(card.getCard1().replace("WM",catename+"-"));
                        }
                        if(wr){
                            print(true,"外码:"+card.getCard1()+",内码:"+card.getCard2()+"写入成功!");
                            cardRequest = new CardRequest();
                            cardRequest.setOut(card.getCard1());
                            cardRequest.setInner(card.getCard2());
                            cardRequest.setState("0");
                            if(cateId!=null){
                                cardRequest.setCate_id(cateId);
                            }
                            request(SAVE_CODE);
                        }else{
                            print(false,"写入失败！可能您已经移开了卡片");
                        }
                    }
                }
                break;
        }
    }

    private Map<String,String> hasPrint = new HashMap<>();
    private AlertDialog printAlert;
    //打印二维码
    private void printQrCode(String code){
        NLog.e("qrcode",code);
        //扫码枪扫的不打印
        if(isShaoMa){
            return;
        }
        if(ISCONNECT){
            //已打印的提示一下
            if(hasPrint.get(code)!=null){

                    printAlert = new AlertDialog(AdminActivity.this);
                    printAlert.setTitle("系统提示");
                    printAlert.setContent("该卡片编码"+code+"已打印，是否重新打印?");
                    printAlert.setSubmitTxt("重新打印");
                    printAlert.setCancelTxt("取消");
                    printAlert.hideJihuo();
                    printAlert.setOnResult(new BaseDialog.OnResult() {
                        @Override
                        public void onActive() {

                        }

                        @Override
                        public void onYes() {
                            toprint(printAlert.getTempData());
                        }

                        @Override
                        public void onNo() {

                        }
                    });
                printAlert.setTempData(code);
                printAlert.show(0,Gravity.CENTER);
            }else{
                toprint(code);
            }
        }else{
            print(false,code+":请先连接蓝牙打印机设备...");
        }
    }

    private void toprint(final String code){
        hasPrint.put(code,code);
        print(true,code+":正在打印卡片二维码...");
        myBinder.WriteSendData(new TaskCallback() {
            @Override
            public void OnSucceed() {
                Toast.makeText(getApplicationContext(),"发送成功!",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void OnFailed() {
                Toast.makeText(getApplicationContext(),"发送失败!",Toast.LENGTH_SHORT).show();
            }
        }, new ProcessData() {
            @Override
            public List<byte[]> processDataBeforeSend() {
                List<byte[]> list = new ArrayList<>();
                //设置标签纸大小
                list.add(DataForSendToPrinterTSC.sizeBymm(40,30));
                //设置间隙
                list.add(DataForSendToPrinterTSC.gapBymm(2,0));
                //清除缓存
                list.add(DataForSendToPrinterTSC.cls());
                //设置方向
                list.add(DataForSendToPrinterTSC.direction(0));
                //具体参数值请参看编程手册
                list.add(DataForSendToPrinterTSC.qrCode(60,30,"H",7,"A",0,"M1","S7",code));
                list.add(DataForSendToPrinterTSC.text(280,200,"TSS24.BF2",270,1,1,code));
                //打印
                list.add(DataForSendToPrinterTSC.print(1));

                return list;
            }
        });
    }

    private List<CardInfo> cardInfoList ;
    private List<Admin> lastAdmin = new ArrayList<>();
    private List<Cate> lastCate = new ArrayList<>();
    @Bind(R.id.img)
    ImageView img;
    @Bind(R.id.listBox)
    LinearLayout listBox;
    @Bind(R.id.list)
    LinearLayout list;
    private LayoutInflater inflate;
    private boolean check(CardInfo cardInfo){
        if(cardInfoList==null){
            return false;
        }
        for(CardInfo cardInfo1:cardInfoList){
            if(cardInfo1.getCard_inner().equals(cardInfo.getCard_inner())){
                return true;
            }
        }
        return false;
    }
    //显示已添加的卡片信息
    private void toPrintCardInfo() {
        if(cardInfoList==null||cardInfoList.size()==0){
            list.removeAllViews();
            img.setVisibility(View.VISIBLE);
            listBox.setVisibility(View.GONE);
            return;
        }
        img.setVisibility(View.GONE);
        listBox.setVisibility(View.VISIBLE);
        list.removeAllViews();
        int i = 0 ;
        for(CardInfo cardInfo1:cardInfoList){
            View view = inflate.inflate(R.layout.item, null);
            TextView title = view.findViewById(R.id.title);
            title.setText("卡号:"+cardInfo1.getCard_inner());
            ImageView remove = view.findViewById(R.id.remove);
            remove.setTag(i);
            remove.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = (int)v.getTag();
                    if(cardInfoList!=null&&cardInfoList.size()>position) {
                        cardInfoList.remove(position);
                    }
                    toPrintCardInfo();
                }
            });
            i++;
            list.addView(view);
        }

    }
    @OnClick(R.id.select)
    public void toJiHuo(){
        if(cardInfoList==null){
            print(false,"请先感应卡再批量激活...");
            return;
        }
        cardListRequest = new ArrayList<>();
        for(CardInfo cardInfo:cardInfoList){
            CardRequest request = new CardRequest();
            request.setId(cardInfo.getCard_id()+"");
            request.setState(1+"");
            request.setOut(cardInfo.getCard_out());
            request.setInner(cardInfo.getCard_inner());
            request.setShare_user_id(cardInfo.getShare_user_id());
            cardListRequest.add(request);
        }

        if(selectDialog==null){
            selectDialog = new SelectDialog(AdminActivity.this);
            selectDialog.setTitle("请选择所属经销商");
            selectDialog.setOnSelect(new SelectDialog.OnSelect() {
                @Override
                public void select(String uid,String name) {
                    selectDialog.dismiss();

                    String cateName = selectDialog.getTempData();
                    for(int i = 0 ; i < cardListRequest.size();i++){
                        cardListRequest.get(i).setAdmin_id(uid);
                        if(!TextUtils.isEmpty(cateName)){
                            String out = cardListRequest.get(i).getOut();
                            out = out.replace("WM",cateName+"-");
                            cardListRequest.get(i).setOut(out);
                        }
                    }
                    request(SAVE_LIST_CODE);
                }
            });
            String catename = cate.getText().toString();
            selectDialog.setTempData(catename);
            selectDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                }
            });
        }
        selectDialog.setData(lastAdmin);
        selectDialog.show(0,Gravity.CENTER);
    }

    private SelectDialog cateDialog ;
    private String cateId ;
    @Bind(R.id.cate)
    TextView cate;
    @OnClick(R.id.cate)
    public void getCate(){
        request(GET_CATE);
    }
    public void selectCate(){
        if(cateDialog==null){
            cateDialog = new SelectDialog(AdminActivity.this);
            cateDialog.setTitle("请选择所属分类");
            cateDialog.setOnSelect(new SelectDialog.OnSelect() {
                @Override
                public void select(String uid,String name) {
                    cateId = uid;
                    cate.setText(name);
                    SharedPreferencesUtil.putData("cate_id",cateId);
                    SharedPreferencesUtil.putData("cate_name",name);
                    cateDialog.dismiss();
                }
            });
            cateDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                }
            });
        }
        List<Admin> admins = new ArrayList<>();
        for(Cate cate:lastCate){
            Admin admin = new Admin();
            admin.setUser_id(cate.getId()+"");
            admin.setUser_name(cate.getName());
            admins.add(admin);
        }
        cateDialog.setData(admins);
        cateDialog.show(0,Gravity.CENTER);
    }

    @Bind(R.id.scrollView)
    ScrollView scrollView;
    private void print(boolean ok,String t){
        String date = DateUtil.format(new Date(),null);
        log.append(Output.formatText("["+date+"]->"+t+"\n",ok?getResources().getColor(R.color.colorPrimary):getResources().getColor(R.color.colorAccent)));
        scrollView.fullScroll(ScrollView.FOCUS_DOWN);
    }



    @Override
    public void onFailure(int requestCode, int state, Object result) {
        super.onFailure(requestCode, state, result);
        switch (requestCode){
            case LOGIN_OUT:
                break;
            case SAVE_LIST_CODE:
                print(false,"网络错误,卡片绑定进销商失败！");
                break;
            case SAVE_CODE:
                if(isActivie){
                    isActivie = false;
                    print(false,"网络错误,卡片激活失败！");
                }else{
                    print(false,"网络错误,保存到云端失败！");
                }
                break;
            case GET_CODE:
                print(false,"网络错误,获取编码失败！");
                break;
        }
    }

    private Tag detectedTag;
    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        readCard(intent);
    }


    private boolean isActivie = false;
    private void readCard(Intent intent){
        String value = readNfcTag(intent);
        print(true,"已识别到卡片,正在操作请勿移开...");
        if(!TextUtils.isEmpty(value)){
            isActivie = true;
            cardId = value;
            isShaoMa = false;
            request(GET_CODE);
        }else{
            cardId="";
            isShaoMa = false;
            request(GET_CODE);
        }
    }
    private boolean writeCard( Tag detectedTag){
        NdefMessage ndefMessage = new NdefMessage(
                new NdefRecord[]{createTextRecord(code)});
        boolean result = writeTag(ndefMessage, detectedTag);
        return result;
    }

    /**
     * 创建NDEF文本数据
     *
     * @param text
     * @return
     */
    public static NdefRecord createTextRecord(String text) {
        byte[] langBytes = Locale.CHINA.getLanguage().getBytes(Charset.forName("US-ASCII"));
        Charset utfEncoding = Charset.forName("UTF-8");
        //将文本转换为UTF-8格式
        byte[] textBytes = text.getBytes(utfEncoding);
        //设置状态字节编码最高位数为0
        int utfBit = 0;
        //定义状态字节
        char status = (char) (utfBit + langBytes.length);
        byte[] data = new byte[1 + langBytes.length + textBytes.length];
        //设置第一个状态字节，先将状态码转换成字节
        data[0] = (byte) status;
        //设置语言编码，使用数组拷贝方法，从0开始拷贝到data中，拷贝到data的1到langBytes.length的位置
        System.arraycopy(langBytes, 0, data, 1, langBytes.length);
        //设置文本字节，使用数组拷贝方法，从0开始拷贝到data中，拷贝到data的1 + langBytes.length
        //到textBytes.length的位置
        System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);
        //通过字节传入NdefRecord对象
        //NdefRecord.RTD_TEXT：传入类型 读写
        NdefRecord ndefRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
                NdefRecord.RTD_TEXT, new byte[0], data);
        return ndefRecord;
    }

    /**
     * 写数据
     *
     * @param ndefMessage 创建好的NDEF文本数据
     * @param tag         标签
     * @return
     */
    public static boolean writeTag(NdefMessage ndefMessage, Tag tag) {
        try {
            Ndef ndef = Ndef.get(tag);
            ndef.connect();
            ndef.writeNdefMessage(ndefMessage);
            return true;
        } catch (Exception e) {
        }
        return false;
    }
    /**
     * 读取NFC标签文本数据
     */
    private String readNfcTag(Intent intent) {
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
                    NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage msgs[] = null;
            int contentSize = 0;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                    contentSize += msgs[i].toByteArray().length;
                }
            }
            try {
                if (msgs != null) {
                    NdefRecord record = msgs[0].getRecords()[0];
                    String textRecord = parseTextRecord(record);
                    return textRecord;
                }
            } catch (Exception e) {
            }
        }
        return null;
    }

    /**
     * 解析NDEF文本数据，从第三个字节开始，后面的文本数据
     *
     * @param ndefRecord
     * @return
     */
    public static String parseTextRecord(NdefRecord ndefRecord) {
        /**
         * 判断数据是否为NDEF格式
         */
        //判断TNF
        if (ndefRecord.getTnf() != NdefRecord.TNF_WELL_KNOWN) {
            return null;
        }
        //判断可变的长度的类型
        if (!Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
            return null;
        }
        try {
            //获得字节数组，然后进行分析
            byte[] payload = ndefRecord.getPayload();
            //下面开始NDEF文本数据第一个字节，状态字节
            //判断文本是基于UTF-8还是UTF-16的，取第一个字节"位与"上16进制的80，16进制的80也就是最高位是1，
            //其他位都是0，所以进行"位与"运算后就会保留最高位
            String textEncoding = ((payload[0] & 0x80) == 0) ? "UTF-8" : "UTF-16";
            //3f最高两位是0，第六位是1，所以进行"位与"运算后获得第六位
            int languageCodeLength = payload[0] & 0x3f;
            //下面开始NDEF文本数据第二个字节，语言编码
            //获得语言编码
            String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
            //下面开始NDEF文本数据后面的字节，解析出文本
            String textRecord = new String(payload, languageCodeLength + 1,
                    payload.length - languageCodeLength - 1, textEncoding);
            return textRecord;
        } catch (Exception e) {
            throw new IllegalArgumentException();
        }
    }


    ////////////////////////////////////////连接蓝牙设备////////////////////////////////////////

    /**
     * 连接蓝牙
     */
    private boolean ISCONNECT = false;
    private void disConnect(){
        if (ISCONNECT){
            myBinder.DisconnectCurrentPort(new TaskCallback() {
                @Override
                public void OnSucceed() {
                    ISCONNECT = false;
                    Toast.makeText(getApplicationContext(),"已断开连接",Toast.LENGTH_SHORT).show();
                }

                @Override
                public void OnFailed() {
                    ISCONNECT = true;
                    Toast.makeText(getApplicationContext(),"断开连接失败",Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
    private void connectPrinter(){
        disConnect();
        String BtAdress=printerMac;
        if (BtAdress.equals(null)||BtAdress.equals("")){
            Toast.makeText(getApplicationContext(),getString(R.string.con_failed),Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(getApplicationContext(),"正在连接打印机..PIN码可能是 0000,如无法连接请联系供应商",Toast.LENGTH_LONG).show();
            myBinder.ConnectBtPort(BtAdress, new TaskCallback() {
                @Override
                public void OnSucceed() {
                    ISCONNECT=true;
                    connect.setText("已连接打印机");
                    Toast.makeText(getApplicationContext(),"连接打印机成功",Toast.LENGTH_SHORT).show();
                }

                @Override
                public void OnFailed() {
                    ISCONNECT=false;
                    connect.setText("连接打印机失败");
                    Toast.makeText(getApplicationContext(),"连接打印机失败",Toast.LENGTH_SHORT).show();
                }
            } );
        }
    }


    private List<String> btList = new ArrayList<>();
    private ArrayList<String> btFoundList = new ArrayList<>();
    private ArrayAdapter<String> BtBoudAdapter ,BtfoundAdapter;
    private View BtDialogView;
    private ListView BtBoundLv,BtFoundLv;
    private LinearLayout ll_BtFound;
    private android.app.AlertDialog btdialog;
    private Button btScan;
    private DeviceReceiver BtReciever;
    private BluetoothAdapter bluetoothAdapter;
    public void setBluetooth(){
        bluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
        //判断时候打开蓝牙设备
        if (!bluetoothAdapter.isEnabled()){
            //请求用户开启
            Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, 1);
        }else {

            showblueboothlist();

        }
    }

    private void showblueboothlist() {
        if (!bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.startDiscovery();
        }
        LayoutInflater inflater=LayoutInflater.from(this);
        BtDialogView=inflater.inflate(R.layout.printer_list, null);
        BtBoudAdapter=new ArrayAdapter<String>(this, R.layout.list_item, btList);
        BtBoundLv= BtDialogView.findViewById(R.id.listView1);
        btScan= BtDialogView.findViewById(R.id.btn_scan);
        ll_BtFound= BtDialogView.findViewById(R.id.ll1);
        BtFoundLv=(ListView) BtDialogView.findViewById(R.id.listView2);
        BtfoundAdapter=new ArrayAdapter<String>(this, R.layout.list_item, btFoundList);
        BtBoundLv.setAdapter(BtBoudAdapter);
        BtFoundLv.setAdapter(BtfoundAdapter);
        btdialog=new android.app.AlertDialog.Builder(this,android.R.style.Theme_Material_Light_DarkActionBar).setTitle("请选择蓝牙打印机设备").setView(BtDialogView).create();
        btdialog.show();

        BtReciever=new DeviceReceiver(btFoundList,BtfoundAdapter,BtFoundLv);

        //注册蓝牙广播接收者
        IntentFilter filterStart=new IntentFilter(BluetoothDevice.ACTION_FOUND);
        IntentFilter filterEnd=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(BtReciever, filterStart);
        registerReceiver(BtReciever, filterEnd);

        setDlistener();
        findAvalibleDevice();
    }
    private void setDlistener() {
        // TODO Auto-generated method stub
        btScan.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                ll_BtFound.setVisibility(View.VISIBLE);
                //btn_scan.setVisibility(View.GONE);
            }
        });
        //已配对的设备的点击连接
        BtBoundLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                // TODO Auto-generated method stub
                try {
                    if(bluetoothAdapter!=null&&bluetoothAdapter.isDiscovering()){
                        bluetoothAdapter.cancelDiscovery();

                    }

                    String mac=btList.get(arg2);
                    mac=mac.substring(mac.length()-17);
//                    String name=msg.substring(0, msg.length()-18);
                    //lv1.setSelection(arg2);
                    btdialog.cancel();
                    printerMac = mac;
                    connectPrinter();
                    SharedPreferencesUtil.putData(Const.MAC,mac);
                    //adrress.setText(mac);
                    //Log.i("TAG", "mac="+mac);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        //未配对的设备，点击，配对，再连接
        BtFoundLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                // TODO Auto-generated method stub
                try {
                    if(bluetoothAdapter!=null&&bluetoothAdapter.isDiscovering()){
                        bluetoothAdapter.cancelDiscovery();

                    }
                    String mac;
                    String msg=btFoundList.get(arg2);
                    mac=msg.substring(msg.length()-17);
                    String name=msg.substring(0, msg.length()-18);
                    //lv2.setSelection(arg2);
                    btdialog.cancel();
                    printerMac = mac;
                    connectPrinter();
                    SharedPreferencesUtil.putData(Const.MAC,mac);
                    Log.i("TAG", "mac="+mac);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

    /*
    找可连接的蓝牙设备
     */
    private void findAvalibleDevice() {
        // TODO Auto-generated method stub
        //获取可配对蓝牙设备
        Set<BluetoothDevice> device=bluetoothAdapter.getBondedDevices();

        btList.clear();
        if(bluetoothAdapter!=null&&bluetoothAdapter.isDiscovering()){
            BtBoudAdapter.notifyDataSetChanged();
        }
        if(device.size()>0){
            //存在已经配对过的蓝牙设备
            for(Iterator<BluetoothDevice> it = device.iterator(); it.hasNext();){
                BluetoothDevice btd=it.next();
                btList.add(btd.getName()+'\n'+btd.getAddress());
                BtBoudAdapter.notifyDataSetChanged();
            }
        }else{  //不存在已经配对过的蓝牙设备
            btList.add("No can be matched to use bluetooth");
            BtBoudAdapter.notifyDataSetChanged();
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode== Activity.RESULT_OK){
            if(requestCode==REQUEST_CODE){
                if (data != null) {
                    String code = data.getStringExtra(Constant.CODED_CONTENT);
                    if(!TextUtils.isEmpty(code)) {
                        onScanSuccess(code);
                    }else {
                        print(false,"扫码内容为空!");
                    }
                }
            }
        }
    }
    private static final int REQUEST_CODE = 1001 ;
    @OnClick(R.id.scan)
    public void scanClick(){
        CheckPermissionUtil.check(AdminActivity.this, new String[]{Permission.CAMERA}, new CheckPermissionUtil.AfterDo() {
            @Override
            public void doIt() {
                openC();
            }
        });
    }
    private void openC(){
        Intent intent = new Intent(this, CaptureActivity.class);
        intent.putExtra(CaptureActivity.EXTRA_IMAGE_TITLE,"扫描条码/二维码");
        intent.putExtra(CaptureActivity.EXTRA_IMAGE_TYPE,0);
        startActivityForResult(intent,REQUEST_CODE);
    }
}
